package com.aidex.biz.service.impl;

import com.aidex.biz.service.ReptileService;
import com.aidex.common.utils.uuid.IdUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class ReptileServiceImpl implements ReptileService {

    @Override
    public List<String> runReptileByJd(String keyword) throws IOException, InterruptedException {
        Thread.sleep((long) (Math.random() * 1000 - 1));
        List<String> stringList = new ArrayList<>();
        String url =
                "https://search.jd.com/Search?keyword=" + keyword + "&enc=utf-8&wq=" + keyword + "&pvid=" + IdUtils.randomUUID();
        Document document =
                Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) " + "Gecko" + "/20070725 Firefox/2.0.0.6").get();
        Elements divs = document.getElementsByClass("p-name-type-2");
        int count = 0;
        for (Element element : divs) {
            Element a = element.child(0);
            stringList.add(a.attr("href").replace("//", ""));
            if (count == 4) {
                break;
            }
            count++;
        }
        return stringList;
    }
}
